<?php
namespace app\mingteng\controller;

use think\Page;
use think\Db;
use think\Session;

class Admin extends Base {
    //初始化
    public function _initialize(){
        parent::_initialize();
        $this->group = array('system'=>'系统设置','content'=>'内容管理','admin'=>'权限管理','ad'=>'广告管理','goods'=>'商品管理','rechargeable'=>'充值卡管理');
    }

    public function index(){
        $list = array();
        $keywords = I('keywords/s');
        if(empty($keywords)){
            $res = D('admin')->select();
        }else{
            $res = DB::name('admin')->where('user_name','like','%'.$keywords.'%')->order('admin_id')->select();
        }
        $role = D('admin_role')->getField('role_id,role_name');
        if($res && $role){
            foreach ($res as $val){
                $val['role'] =  $role[$val['role_id']];
                $val['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
                $list[] = $val;
            }
        }
        $this->assign('list',$list);
        return $this->fetch();
    }

    public function admin_info(){
        $admin_id = I('get.admin_id/d',0);
        if($admin_id){
            $info = D('admin')->where("admin_id", $admin_id)->find();
            $info['password'] =  "";
            $this->assign('info',$info);
        }
        $act = empty($admin_id) ? 'add' : 'edit';
        $this->assign('act',$act);
        $role = D('admin_role')->select();
        $this->assign('role',$role);
        return $this->fetch();
    }

    public function adminHandle(){
        $data = I('post.');
        if(empty($data['password'])){
            unset($data['password']);
        }else{
            $data['ec_salt'] = get_rand_str(6,0,1);
            $data['password'] = encrypt($data['password'].$data['ec_salt']);
        }
        if($data['act'] == 'add'){
            unset($data['admin_id']);
            $data['add_time'] = time();
            if(D('admin')->where("user_name", $data['user_name'])->count()){
                $this->error("此用户名已被注册，请更换",U('Admin/admin_info'));
            }else{
                $r = D('admin')->add($data);
            }
        }

        if($data['act'] == 'edit'){
            $r = D('admin')->where('admin_id', $data['admin_id'])->save($data);
        }

        if($data['act'] == 'del' && $data['del_id']>1){
            D('admin')->where('admin_id', $data['del_id'])->delete();
            exit(json_encode(1));
        }

        if($r){
            $this->success("操作成功",U('Admin/index'));
        }else{
            $this->error("操作失败",U('Admin/index'));
        }
    }


    /*
     * 管理员登陆
     */
    public function login(){
    
        if(session('?admin_id') && session('admin_id')>0){
            $this->error("您已登录",U('Index/index'));
        }

        if(IS_AJAX){
            if (!check(I('post.code'), "admin_login")) {
                ajaxReturn(array('status'=>0,'msg'=>'验证码错误'));
            }
            $condition['user_name'] = I('post.username/s');
            $condition['password'] = I('post.password/s');
            if(!empty($condition['user_name']) && !empty($condition['password'])){
                $ec_salt = M('admin')->where('user_name',$condition['user_name'])->getField('ec_salt');
                $condition['password'] = encrypt($condition['password'].$ec_salt);
//                pr($condition['password'],1);
               // unset($condition['password']);

                $admin_info = M('admin')->join(PREFIX.'admin_role', PREFIX.'admin.role_id='.PREFIX.'admin_role.role_id','INNER')->where($condition)->find();
                if(is_array($admin_info)){
                    session('admin_id',$admin_info['admin_id']);
                    session('act_list',$admin_info['act_list']);
                    M('admin')->where("admin_id = ".$admin_info['admin_id'])->save(array('last_login'=>time(),'last_ip'=>  request()->ip()));
                    adminLog('后台登录');
                    ajaxReturn(array('status'=>1,'result'=>U('Index/index'),'msg'=>'登录成功！'));
                }else{
                    ajaxReturn(array('status'=>0,'msg'=>'账号密码不正确'));
                }
            }else{
                ajaxReturn(array('status'=>0,'msg'=>'请填写账号密码'));
            }
        }

        return $this->fetch();
    }

    /**
     * 退出登陆
     */
    public function logout(){
        session_unset();
        session_destroy();
        session::clear();
        $this->success("退出成功",U('Admin/login'));
    }

    /**
     * 验证码获取
     */
    public function verify(){
        verify("admin_login");
    }

    public function role(){
        $list = D('admin_role')->order('role_id desc')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }

    public function role_info(){
        $role_id = I('get.role_id/d');
        $detail = array();
        if($role_id){
            $detail = M('admin_role')->where("role_id",$role_id)->find();
            $detail['act_list'] = explode(',', $detail['act_list']);
            $this->assign('detail',$detail);
        }
        $right = M('system_menu')->order('id')->select();
        foreach ($right as $val){
            if(!empty($detail)){
                $val['enable'] = in_array($val['id'], $detail['act_list']);
            }
            $modules[$val['group']][] = $val;
        }
        $this->assign('group',$this->group);
        $this->assign('modules',$modules);
        return $this->fetch();
    }

    public function roleSave(){
        $data = I('post.');
        $res = $data['data'];
        $res['act_list'] = is_array($data['right']) ? implode(',', $data['right']) : '';
        if(empty($res['act_list']))
            $this->error("请选择权限!");
        if(empty($data['role_id'])){
            $admin_role = Db::name('admin_role')->where(['role_name'=>$res['role_name']])->find();
            if($admin_role){
                $this->error("已存在相同的角色名称!");
            }else{
                $r = D('admin_role')->add($res);
            }
        }else{
            $admin_role = Db::name('admin_role')->where(['role_name'=>$res['role_name'],'role_id'=>['<>',$data['role_id']]])->find();
            if($admin_role){
                $this->error("已存在相同的角色名称!");
            }else{
                $r = D('admin_role')->where('role_id', $data['role_id'])->save($res);
            }
        }
        if($r){
            adminLog('管理角色');
            $this->success("操作成功!",U('Admin/role_info',array('role_id'=>$data['role_id'])));
        }else{
            $this->error("操作失败!",U('Admin/role'));
        }
    }

    public function roleDel(){
        $role_id = I('post.del_id/d');
        $admin = D('admin')->where('role_id',$role_id)->find();
        if($admin){
            exit(json_encode("请先清空所属该角色的管理员"));
        }else{
            $d = M('admin_role')->where("role_id", $role_id)->delete();
            if($d){
                exit(json_encode(1));
            }else{
                exit(json_encode("删除失败"));
            }
        }
    }
    //操作日志
    public function log(){
        $p = I('p/d',1);
        $logs = DB::name('admin_log')->alias('l')->join('__ADMIN__ a','a.admin_id =l.admin_id')->order('log_time DESC')->page($p.',20')->select();
        $this->assign('list',$logs);
        $count = DB::name('admin_log')->count();
        $Page = new Page($count,20);
        $show = $Page->show();
        $this->assign('pager',$Page);
        $this->assign('page',$show);
        return $this->fetch();
    }
    public function logDel(){
        $id = I('del_id/d');
        if(M('admin_log')->where(['log_id'=>$id])->delete()){
            ajaxReturn(1);
        }
        ajaxReturn('参数错误！'.$id);
    }

    //权限列表
    public function right_list(){
        $name = I('name');
        if($name){
            $condition['name|right'] = array('like',"%$name%");
            $right_list = M('system_menu')->where($condition)->order('id desc')->select();
        }else{
            $right_list = M('system_menu')->order('id desc')->select();
        }

        $this->assign('right_list',$right_list);
        $this->assign('group',$this->group);
        return $this->fetch();
    }

    public function edit_right(){
        if(IS_POST){
            $data = I('post.');
            $data['right'] = implode(',',$data['right']);
            if(!empty($data['id'])){
                M('system_menu')->where(array('id'=>$data['id']))->save($data);
            }else{
                if(M('system_menu')->where(array('name'=>$data['name']))->count()>0){
                    $this->error('该权限名称已添加，请检查',U('Admin/right_list'));
                }
                unset($data['id']);
                M('system_menu')->add($data);
            }
            $this->success('操作成功',U('Admin/right_list'));
            exit;
        }
        $id = I('id');
        if($id){
            $info = M('system_menu')->where(array('id'=>$id))->find();
            $info['right'] = explode(',', $info['right']);
            $this->assign('info',$info);
        }
        $planPath = APP_PATH.'mingteng/controller';
        $planList = array();
        $dirRes   = opendir($planPath);
        while($dir = readdir($dirRes))
        {
            if(!in_array($dir,array('.','..','.svn')))
            {
                $planList[] = basename($dir,'.php');
            }
        }
        $this->assign('planList',$planList);
        $this->assign('group',$this->group);
        return $this->fetch();
    }

    public function right_del(){
        $id = I('del_id');
        if(is_array($id)){
            $id = implode(',', $id);
        }
        if(!empty($id)){
            $r = M('system_menu')->where("id in ($id)")->delete();
            if($r){
                ajaxReturn(1);
            }else{
                ajaxReturn('删除失败');
            }
        }else{
            ajaxReturn('参数有误');
        }
    }
    public function ajax_get_action(){
        $control = I('controller');
        $advContrl = get_class_methods("app\\mingteng\\controller\\".str_replace('.php','',$control));
        $baseContrl = get_class_methods('app\mingteng\controller\Base');
        $diffArray  = array_diff($advContrl,$baseContrl);
        $html = '';
        foreach ($diffArray as $val){
            $html .= "<option value='".$val."'>".$val."</option>";
        }
        exit($html);
    }
}